package com.fingard.csp.common.log;


import com.fingard.csp.common.date.Format;
import com.fingard.csp.common.io.FileHelper;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 日志工具包
 *
 * @author fanghh
 * @date 2020.5.13
 * @version 1.0
 */
public class LogHelper {
    /**
     * 异常堆栈输出到字符串
     */
    public static String getStackTrace(Throwable e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } catch (Exception ex) {
            System.out.println("异常:\r\n" + ex.getMessage());
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        if (sw != null) {
            return sw.toString();
        }
        return "";
    }

    public static String getErrMsg(String fileName) {
        RandomAccessFile r = null;

        try {
            r = new RandomAccessFile(fileName, "r");
            long start = r.getFilePointer();
            long nextend = start + r.length() - 1;
            r.seek(nextend);
            int c = -1;
            List<String> list = new ArrayList<String>();
            boolean isOpened = false;
            while (nextend >= start) {
                c = r.read();
                if (c == '\n' || c == '\r') {
                    String tmpLine = r.readLine();
                    if(tmpLine == null) {
                        continue;
                    }
                    String result = new String(tmpLine.getBytes("ISO-8859-1"),"utf-8");
                    if (result.contains("[ERROR] [Help 1]")) {
                        isOpened = true;
                    }
                    if(isOpened) {
                        list.add(result);
                    }
                    if (result.contains("[ERROR] COMPILATION ERROR :")) {
                        break;
                    }
                    nextend--;
                }
                nextend--;
                if (nextend >= 0) {
                    r.seek(nextend);
                    if (nextend == 0) {// 当文件指针退至文件开始处，输出第一行
                        System.out.println(r.readLine());
                    }
                }
            }
            StringBuilder sbMsg = new StringBuilder();
            for(int i=list.size()-1;i>=0;i--) {
                sbMsg.append(list.get(i)).append("\r\n");
            }

            String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();// web-inf/classes
            String logFileName = Format.DateTime17SSSFormat.format(new Date())+".txt";
            String tmpPath = new File(filePath).getParentFile().getParentFile().getAbsolutePath()+File.separator+"errlogs" +File.separator+logFileName;
            FileHelper.writeFile(tmpPath,sbMsg.toString(),"utf-8");
            String targetUrl = tmpPath.substring(tmpPath.indexOf("errlogs"));
            targetUrl = "http://insu.fingard.net:9561/csp/"+targetUrl;
            return targetUrl;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("异常:\r\n" + ex.getMessage());
        } finally {
            if (r != null)
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}